//
//  UserAuditViewController.m
//  CMVRFForIOS
//
//  Created by HailongHan on 15/4/19.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "UserAuditViewController.h"
#import <TPKeyboardAvoidingTableView.h>
#import "DefaultStyleTableViewCell.h"
#import "UserProfileData.h"
#import <MBProgressHUD.h>
#import "MJRefresh.h"

@interface UserAuditViewController () {
    MBProgressHUD *HUD;
    NSUInteger beginIndex;
    NSUInteger endIndex;
    NSUInteger approvedBegin;
    NSUInteger approvedEnd;
}

/**
 *  切换button
 */
@property (strong, nonatomic) UISegmentedControl *segmentControl;

//@property (nonatomic,strong) UISearchBar *productSearchBar;
@property (nonatomic,strong) TPKeyboardAvoidingTableView *tableView;
@property (nonatomic,retain) NSMutableArray *dataSourceApproved;
@property (nonatomic,retain) NSMutableArray *dataSourceNotApproved;
@property (nonatomic,copy) NSString *searchStr;


@end

@implementation UserAuditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
    [self loadData];
}

#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"用户审核";
    
    //适配iOS7uinavigationbar遮挡tableView的问题
    if(IS_IOS7){
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    self.segmentControl = [[UISegmentedControl alloc] initWithItems:@[@"未认证用户", @"已认证用户"]];
    self.navigationItem.titleView = self.segmentControl;
    
    [self.segmentControl addTarget:self action:@selector(switchView) forControlEvents:UIControlEventValueChanged];
    
    //初始显示资讯中心
    [self.segmentControl setSelectedSegmentIndex:0];
    
//    //使用UISearchBar
//    self.productSearchBar = [[UISearchBar alloc]init];
////    //设置bar的frame
//    self.productSearchBar.frame = CGRectMake(0, 0, kScreen_Width, 35);
//    self.productSearchBar.placeholder = @"请输入要搜索的用户名";
//    self.productSearchBar.showsCancelButton = YES;
//    self.productSearchBar.delegate = self;
//    [self.view addSubview:self.productSearchBar];
    
    self.tableView = [[TPKeyboardAvoidingTableView alloc] initWithFrame:[UIView frameWithOutNavTab] style:UITableViewStylePlain];
//    self.tableView.y = 35;
//    self.tableView.height -= 35;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        [self refreshData];
    }];
    //上拉加载
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    
    [self.view addSubview:self.tableView];
}


#pragma mark - 数据处理
- (void)initData {
    self.dataSourceApproved = [NSMutableArray new];
    self.dataSourceNotApproved = [NSMutableArray new];
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    approvedBegin = 0;
    approvedEnd = LIST_PAGE_ITEM_COUNTS - 1;
}

- (void)refreshData {
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        //未认证
        beginIndex = 0;
        endIndex = LIST_PAGE_ITEM_COUNTS - 1;
        [self loadAllUserProfileData:beginIndex andEnd:endIndex andApproved:_segmentControl.selectedSegmentIndex];
    }
    else {
        //已认证
        approvedBegin = 0;
        approvedEnd = LIST_PAGE_ITEM_COUNTS - 1;
        [self loadAllUserProfileData:approvedBegin andEnd:approvedEnd andApproved:_segmentControl.selectedSegmentIndex];
    }
    
}

- (void)loadMoreData {
    
    
    if (_segmentControl.selectedSegmentIndex == 0) {
        //未认证
        if (self.dataSourceNotApproved.count == 0) {
            return;
        }
        // 马上进入刷新状态
        [self.tableView.mj_footer beginRefreshing];
        beginIndex = self.dataSourceNotApproved.count;
        endIndex = beginIndex + LIST_PAGE_ITEM_COUNTS - 1;
        [self loadAllUserProfileData:beginIndex andEnd:endIndex andApproved:_segmentControl.selectedSegmentIndex];
    }
    else {
        //已认证
        if (self.dataSourceApproved.count == 0) {
            return;
        }
        // 马上进入刷新状态
        [self.tableView.mj_footer beginRefreshing];
        approvedBegin = self.dataSourceApproved.count;
        approvedEnd = approvedBegin + LIST_PAGE_ITEM_COUNTS - 1;
        [self loadAllUserProfileData:approvedBegin andEnd:approvedEnd andApproved:_segmentControl.selectedSegmentIndex];
    }
}

- (void)loadData {
    //未认证
    beginIndex = 0;
    endIndex = LIST_PAGE_ITEM_COUNTS - 1;
    [self loadAllUserProfileData:beginIndex andEnd:endIndex andApproved:0];
    //已认证
    approvedBegin = 0;
    approvedEnd = LIST_PAGE_ITEM_COUNTS - 1;
    [self loadAllUserProfileData:approvedBegin andEnd:approvedEnd andApproved:1];
}

- (void)loadAllUserProfileData:(NSInteger)si andEnd:(NSInteger)ei andApproved:(NSInteger)approve {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:[NSNumber numberWithInteger:si] forKey:@"si"];
    [param setValue:[NSNumber numberWithInteger:ei] forKey:@"ei"];
    [param setValue:[NSNumber numberWithInteger:approve] forKey:@"Approved"];
    
    
    [HttpClient getWithUrl:HTTP_GET_ALL_CHILD_USERS_BY_TYPE token:[[AccountManager manager]token] paramDic:param resultClass:[UserProfileData class] success:^(UserProfileData *obj) {
        if (si == 0) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            if (approve == 0) {
                //未认证的用户
                [self.dataSourceNotApproved removeAllObjects];
            }
            else {
                [self.dataSourceApproved removeAllObjects];
            }
        }
        else {
            //上拉加载更多
            [self.tableView.mj_footer endRefreshing];
        }
        if (obj.getChildUserProfiles2Result != nil && obj.getChildUserProfiles2Result.count > 0) {
            if (approve == 0) {
                //未认证的用户
                [self.dataSourceNotApproved addObjectsFromArray:obj.getChildUserProfiles2Result];
            }
            else {
                [self.dataSourceApproved addObjectsFromArray:obj.getChildUserProfiles2Result];
            }
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        if (si == 0) {
            //下拉刷新
            [self.tableView.mj_header endRefreshing];
            if (approve == 0) {
                //未认证的用户
                [self.dataSourceNotApproved removeAllObjects];
            }
            else {
                [self.dataSourceApproved removeAllObjects];
            }
            [self.tableView reloadData];
        }
        else {
            //上拉加载更多
            [self.tableView.mj_footer endRefreshing];
        }
        CMLog(@"获取子用户数据失败：%@", error);
    }];
}

//- (void)loadAllUserProfileData:(NSInteger)si andEnd:(NSInteger)ei {
//    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    [param setValue:[NSNumber numberWithInteger:si] forKey:@"si"];
//    [param setValue:[NSNumber numberWithInteger:ei] forKey:@"ei"];
//    
//    
//    [HttpClient getWithUrl:HTTP_GET_ALL_CHILD_USERS token:[[AccountManager manager]token] paramDic:param resultClass:[UserProfileData class] success:^(UserProfileData *obj) {
//        if (si == 0) {
//            //下拉刷新
//            [self.tableView.mj_header endRefreshing];
//            [self.dataSourceApproved removeAllObjects];
//            [self.dataSourceNotApproved removeAllObjects];
//        }
//        else {
//            //上拉加载更多
//            [self.tableView.mj_footer endRefreshing];
//        }
//        if (obj.getChildUserProfilesResult != nil && obj.getChildUserProfilesResult.count > 0) {
//            [self.dataSourceApproved removeAllObjects];
//            [self.dataSourceNotApproved removeAllObjects];
//            for (UserProfileData *item in obj.getChildUserProfilesResult) {
//                if (item.approved == 1) {
//                    [self.dataSourceApproved addObject:item];
//                }
//                else {
//                    [self.dataSourceNotApproved addObject:item];
//                }
//            }
//        }
//        [self.tableView reloadData];
//    } failure:^(NSError *error) {
//        if (si == 0) {
//            //下拉刷新
//            [self.tableView.mj_header endRefreshing];
//            [self.dataSourceApproved removeAllObjects];
//            [self.dataSourceNotApproved removeAllObjects];
//            [self.tableView reloadData];
//        }
//        else {
//            //上拉加载更多
//            [self.tableView.mj_footer endRefreshing];
//        }
//        CMLog(@"获取子用户数据失败：%@", error);
//    }];
//}

//- (void)searchUserProfileData:(int)si andEnd:(int)ei andKeyword:(NSString*)searchStr {
//    NSMutableDictionary *param = [NSMutableDictionary dictionary];
//    [param setValue:[NSNumber numberWithInt:si] forKey:@"si"];
//    [param setValue:[NSNumber numberWithInt:ei] forKey:@"ei"];
//    
//    [HttpClient getWithUrl:HTTP_GET_SEARCH_CHILD_USERS token:[[AccountManager manager]token] paramDic:param resultClass:[UserProfileData class] success:^(UserProfileData *obj) {
//        if (obj.GetChildUserProfilesResult != nil && obj.GetChildUserProfilesResult.count > 0) {
//            [self.dataSourceApproved removeAllObjects];
//            [self.dataSourceNotApproved removeAllObjects];
//            for (UserProfileData *item in obj.GetChildUserProfilesResult) {
//                if (item.Approved == 1) {
//                    [self.dataSourceApproved addObject:item];
//                }
//                else {
//                    [self.dataSourceNotApproved addObject:item];
//                }
//            }
//            [self.tableView reloadData];
//        }
//    } failure:^(NSError *error) {
//        CMLog(@"获取子用户数据失败：%@", error);
//    }];
//}

- (void)modifyUserApproveData:(int)isApproved forUser:(UserProfileData*)data {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:[NSNumber numberWithInt:isApproved] forKey:@"Approved"];
    [param setValue:[data.userName base64Encoder] forKey:@"un"];
    
    HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    if (isApproved == 1) {
        HUD.labelText = @"设置为认证用户中";
    }
    else {
        HUD.labelText = @"设置为未认证用户中";
    }
    
    [HttpClient getWithUrl:HTTP_GET_APPROVE_USER token:[[AccountManager manager]token] paramDic:param resultClass:[UserProfileData class] success:^(UserProfileData *obj) {
            //成功
        [HUD setHidden:YES];
        data.approved = isApproved;
        if (isApproved == 1) {
            //把当前数据放到已认证数据源中，并从未认证数据源中删除
            [self.dataSourceNotApproved removeObject:data];
            [self.dataSourceApproved addObject:data];
        }
        else {
            [self.dataSourceApproved removeObject:data];
            [self.dataSourceNotApproved addObject:data];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [HUD setHidden:YES];
        [Tools showMessageCenter:@"操作失败！"];
        CMLog(@"设置用户认证数据失败：%@", error);
    }];
}

#pragma mark - 切换事件
-(void)switchView
{
    [self.tableView reloadData];
//    if (_segmentControl.selectedSegmentIndex == 0) {
//        [self.tableView reloadData];
//    } else if (_segmentControl.selectedSegmentIndex == 1) {
//        
//    }
}

#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_segmentControl.selectedSegmentIndex == 0) {
        return self.dataSourceNotApproved.count;
    } else if (_segmentControl.selectedSegmentIndex == 1) {
        return self.dataSourceApproved.count;
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"ProductCell";
    DefaultStyleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[DefaultStyleTableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    UserProfileData *item;
    if (_segmentControl.selectedSegmentIndex == 0) {
        item = [self.dataSourceNotApproved objectAtIndex:indexPath.row];
    } else if (_segmentControl.selectedSegmentIndex == 1) {
        item = [self.dataSourceApproved objectAtIndex:indexPath.row];
    }
    cell.textLabel.text = item.userName;
    cell.textLabel.textColor = CM_BLUE_COLOR;
    NSString *detail;
    if ([item.role isEqualToString:@"Seller"]) {
        //销售人员显示name phone
        detail = [NSString stringWithFormat:@"姓名：%@ 电话：%@", item.contactName, item.phoneNumber];
    }
    else {
        detail = item.name;
    }
    cell.detailTextLabel.text = detail;
    cell.detailTextLabel.hidden = NO;
    
    
    //滑动按钮
    cell.rightUtilityButtons = [self rightButtons];
    cell.delegate = self;
    cell.tag = indexPath.row;
    
    return cell;
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    if (_segmentControl.selectedSegmentIndex == 1) {
        [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"取消认证"];
    }
    else {
        [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"认证用户"];
    }
    return rightUtilityButtons;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //反选
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return CELL_HEIGHT;
}

#pragma mark - 滑动按钮代理协议
/**
 *  右侧滑动按钮点击事件
 *
 *  @param cell  单元cell
 *  @param index 下标
 */
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    switch (index) {
        case 0:{
            UserProfileData *item;
            int approved = 0;
            if (_segmentControl.selectedSegmentIndex == 0) {
                approved = 1;
                item = [self.dataSourceNotApproved objectAtIndex:cell.tag];
            } else if (_segmentControl.selectedSegmentIndex == 1) {
                approved = 0;
                item = [self.dataSourceApproved objectAtIndex:cell.tag];
            }
            [self modifyUserApproveData:approved forUser:item];
            break;
        }
            
        default:
            break;
    }
    [cell hideUtilityButtonsAnimated:YES];
}


/**
 *  滑动的时候把其他的隐藏掉
 *
 *  @param cell cell
 *
 *  @return 隐藏其他的cell
 */
-(BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell{
    return YES;
}


#pragma mark - UISearchBar的代理方法
/**
 *  called when text changes (including clear)
 *
 *  @param searchBar  <#searchBar description#>
 *  @param searchText <#searchText description#>
 */
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    if (searchBar.text.length == 0) {
        //加载所有的用户
        [self loadData];
    }
}
/**
 *  用户编辑时的响应
 *
 *  @param searchBar 控件的ID
 */
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"%@", searchBar.text);
}

/**
 *  called when keyboard search button
 *
 *  @param searchBar <#searchBar description#>
 */
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
//    NSLog(@"%@", searchBar.text);
//    NSLog(@"%@", searchBar.text);
//    if ([self.productSearchBar isFirstResponder]) {
//        [self.productSearchBar resignFirstResponder];
//    }
//    
//    [self searchProducts:searchBar.text];
}


#pragma mark - 触碰屏幕隐藏键盘
//-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
//    if ([self.productSearchBar isFirstResponder]) {
//        [self.productSearchBar resignFirstResponder];
//    }
//    
//}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
